from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from .ser import *
from .models import *


# Create your views here.

#店主展示
class ShopUsermanage(APIView):
    def get(self,request):
        user = ShopUser.objects.all()
        ser = ShopUsermanageSer(user,many=True)
        return Response({'code':200,'list':ser.data})

    def post(self,request):
        data = request.data
        ser = ShopSer(data=data)
        if ser.is_valid():
            ser.save()
        return Response({'code': 200})




#商品展示
class Showmanage(APIView):
    def get(self,request):
        userid= request.GET.get('userid')

        # print(userid)
        if userid:

            goods = Shops.objects.filter(userid_id=userid).all()
            # print(goods)
            ser = ShopmanageSer(goods, many=True)
            return Response({'code': 200, 'list': ser.data})
        else:
            goods = Shops.objects.all()
            ser = ShopmanageSer(goods,many=True)
            return Response({'code':200,'list':ser.data})

    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = ShopUser.objects.filter(username=username).first()
        if user:
           if user.password == password:
                return Response({'code': 200, 'msg': '登录成功','userid':user.id,'uname':user.username})
           else:
               return Response({'code': 10020, 'msg': '账号或密码错误'})
        else:
            return Response({'code': 20020, 'msg': '用户不存在'})

    def delete(self,request):
        id = request.GET.get('id')
        user = Shops.objects.filter(id=id).delete()
        print(user)

        return Response({'code':200})

    def put(self,request):
        types = request.GET.get('type')
        print(type(types),types)
        if types:
            Shops.objects.order_by(types).all()
            return Response({'code': 200})
        else:
            Shops.objects.order_by('-'+types).all()
            return Response({'code': 200})

class Change(APIView):
    def get(self,request):
        types = request.GET.get('type')
        print(type(types),types)
        if types:
            Shops.objects.order_by(types).all()
            return Response({'code': 200})
        else:
            Shops.objects.order_by('-'+str(types)).all()
            return Response({'code': 200})